package com.bianxianmao.duobao.fragment;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.provider.ContactsContract;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.bianxianmao.R;
import com.bianxianmao.base.BaseFragment;
import com.bianxianmao.duobao.activity.ClassfityActivity;
import com.bianxianmao.duobao.activity.DetailActivity;
import com.bianxianmao.duobao.activity.NewrechargeActivity;
import com.bianxianmao.duobao.activity.ShowListActivity;
import com.bianxianmao.duobao.adapter.MyViewPagerAdapter;
import com.bianxianmao.duobao.bean.BannerBean;
import com.bianxianmao.duobao.bean.TrumpetBean;
import com.bianxianmao.find.activity.DoubleActivity;
import com.bianxianmao.lastknow.fragment.Indicator;
import com.bianxianmao.myinfo.activity.CommonQuestionActivity;
import com.bianxianmao.myinfo.activity.UserAccountActivity;
import com.bianxianmao.utils.Constants;
import com.bianxianmao.utils.GlideImageLoder;
import com.squareup.okhttp.Request;
import com.sunfusheng.marqueeview.MarqueeView;
import com.youth.banner.Banner;
import com.youth.banner.listener.OnBannerListener;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017/7/7 0007.
 * 夺宝fragment
 */
public class DuobaoFragment extends BaseFragment implements View.OnClickListener {

    private Banner banner;
    private ImageView newrecharge;
    private TextView classifity;
    private TextView showlist;
    private TextView recharge;
    private TextView pk;
    private TextView service;
    private PopupWindow popupWindow;
    private LinearLayout serviceqq;
    private ImageView fork;
    private LinearLayout qa;
    private LinearLayout servicecall;
    private TextView call;
    private TextView callphone;
    private TextView addtocontact;
    private String phone;
    private TextView newcreate;
    private TextView created;
    private List<String> stringList;
    private WebView webView;
    private int position;
    private int number = 0;
    private boolean isRunning = true;
    private TextView nick;
    private TextView productname;
    private TextView show;
    private MarqueeView marqueeView;

    private ImageView ivArrowtop;
    private ImageView arrowbottom;
    private ViewPager viewpager;
    private RecyclerView rv;

    private ArrayList<BaseFragment> fragments;
    private FragmentManager fragmentManager;
    private MyViewPagerAdapter myViewPagerAdapter;
    private PopularityFragment popularityFragment;

    private SurplusAscFragment surplusFragment;
    private TabLayout tab;
    private ViewPager vp;
    private static DuobaoFragment duobaoFragment;
    private String[] strs;

    @Override
    public View initView() {
        View view = View.inflate(mContext, R.layout.fragment_duobao, null);
        banner = (Banner) view.findViewById(R.id.banner);
        newrecharge = (ImageView) view.findViewById(R.id.iv_new_recharge);
        classifity = (TextView) view.findViewById(R.id.tv_classify);
        showlist = (TextView) view.findViewById(R.id.tv_showlist);
        recharge = (TextView) view.findViewById(R.id.tv_Recharge);
        pk = (TextView) view.findViewById(R.id.tv_pk);
        service = (TextView) view.findViewById(R.id.tv_service);
        productname = (TextView) view.findViewById(R.id.tv_productName);
        marqueeView = (MarqueeView) view.findViewById(R.id.marqueeView);
        vp = (ViewPager) view.findViewById(R.id.vp);
        tab = (TabLayout) view.findViewById(R.id.tab);
        fragments = new ArrayList<>();
        myViewPagerAdapter = new MyViewPagerAdapter(getActivity().getSupportFragmentManager(), fragments, strs);
        vp.setAdapter(myViewPagerAdapter);
        tab.setupWithViewPager(vp);
        fragments.add(new PopularityFragment());
        fragments.add(new SurplusAscFragment());
//        tab.addTab(tab.newTab().setText("人气"));
//        tab.addTab(tab.newTab().setText("剩余"));

//        initFragment();
//
//       vp.setAdapter();
//        tab.setTabGravity(TabLayout.GRAVITY_FILL);//这个地方需要注意
//        //TabLayout和ViewPager关联在一起
//         tab.setupWithViewPager(vp);
//        tab.setTabsFromPagerAdapter(new MyViewPagerAdapter(getActivity().getSupportFragmentManager(),fragments,strs));
        //设置指示器的颜色
//        tab.setSelectedTabIndicatorColor(R.color.textColor_selected);
////        //设置指示器的高度
////        tab.setSelectedTabIndicatorHeight(2);
//        //设置文字颜色
//        tab.setTabTextColors(Color.BLACK, R.color.textColor_selected);
        //导航模式
        tab.setTabMode(TabLayout.MODE_FIXED);
        tab.post(new Runnable() {
            @Override
            public void run() {
                Indicator.setIndicator(tab, 30, 30);
            }
        });
        tab.setOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(vp) {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                super.onTabSelected(tab);
            }
        });
//        tab.setupWithViewPager(vp);
//        tab.setTabsFromPagerAdapter(new MyViewPagerAdapter(getFragmentManager(),fragments));
//
//        ivArrowtop = (ImageView) view.findViewById(R.id.iv_arrowtop);
//        arrowbottom = (ImageView) view.findViewById(R.id.iv_arrowbottom);

        newrecharge.setOnClickListener(this);
        classifity.setOnClickListener(this);
        recharge.setOnClickListener(this);
        service.setOnClickListener(this);
        showlist.setOnClickListener(this);
        pk.setOnClickListener(this);
        //上面箭头
//        arrowbottom.setOnClickListener(this);
//        //下方箭头
//        ivArrowtop.setOnClickListener(this);
//        initFragment();

        return view;
    }
//    //创建Fragment对象
//    public  static Fragment setFragment(){
//        if (duobaoFragment==null)
//            synchronized (DuobaoFragment.class){
//                if (duobaoFragment==null){
//                    duobaoFragment=new DuobaoFragment();
//                }
//            }
//        return duobaoFragment;
//    }
//    //初始化fragment
//    private void initFragment() {
//        if (duobaoFragment==null)
//            synchronized (DuobaoFragment.class){
//                if (duobaoFragment==null){
//                    duobaoFragment=new DuobaoFragment();
//                }
//            }
//    }

    //初始化pupowindow

    private void initPopuWindow(View parent) {
        View v = getActivity().getLayoutInflater().inflate(
                R.layout.service, null);
        fork = (ImageView) v.findViewById(R.id.iv_fork);
        qa = (LinearLayout) v.findViewById(R.id.ll_qa);
        servicecall = (LinearLayout) v.findViewById(R.id.ll_servicecall);
        call = (TextView) v.findViewById(R.id.tv_servicecall);
        qa.setOnClickListener(this);
        servicecall.setOnClickListener(this);
        fork.setOnClickListener(this);
        popupWindow = new PopupWindow(v, LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT, false);
        popupWindow.setFocusable(true);
        // 该属性设置为true则你在点击屏幕的空白位置也会退出
        popupWindow.setTouchable(true);
        popupWindow.setOutsideTouchable(true);
        // 设置背景颜色变暗
        WindowManager.LayoutParams lp = getActivity().getWindow().getAttributes();
        lp.alpha = 0.7f;
        getActivity().getWindow().setAttributes(lp);
        popupWindow.showAtLocation(parent, Gravity.CENTER, 0, 0);
    }

    //显示对话框
    public void showDialog(Context mContext) {
        LayoutInflater inflater = LayoutInflater.from(mContext);
        View view = inflater.inflate(R.layout.alert_call, null);
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setView(view);
        builder.create();
        callphone = (TextView) view.findViewById(R.id.tv_callphone);
        addtocontact = (TextView) view.findViewById(R.id.tv_addto_contact);
        callphone.setOnClickListener(this);
        addtocontact.setOnClickListener(this);
        builder.show();
    }

    //打电话
    private void call(String phone) {
        Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phone));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }

    //创建联系人
    private void createcontact() {
        LayoutInflater inflater = LayoutInflater.from(mContext);
        View view = inflater.inflate(R.layout.alert_create_contact, null);
        newcreate = (TextView) view.findViewById(R.id.tv_newcreate);
        created = (TextView) view.findViewById(R.id.tv_created);
        newcreate.setOnClickListener(this);
        created.setOnClickListener(this);
        new AlertDialog.Builder(mContext).setView(view).show();
    }

    public boolean onKeyDown(int keyCoder, KeyEvent event) {
        if (webView.canGoBack() && keyCoder == KeyEvent.KEYCODE_BACK) {
            webView.goBack();   //goBack()表示返回webView的上一页面
            return true;
        }
        return false;
    }

    // Web视图
    private class MyWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }
    }

    @Override
    public void initData() {

        //得到网络连接
        getDataFromNet();
        initTrumpet();
    }

    private void getDataFromNet() {

        String url = Constants.BANNER_URL;
        OkHttpUtils.get().url(url).build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Request request, Exception e) {
                        //Log.e(TAG, "首页请求失败==" + e.getMessage());
                    }

                    @Override
                    public void onResponse(String response) {
//                        Log.e("222", "首页请求成功==" + response);
                        //解析数据
                        processData(response);
//                        initPopularity();
                    }

                    private void processData(String json) {
                        BannerBean bannerBean = JSON.parseObject(json, BannerBean.class);
                        final List<BannerBean.ReturnValueBean> returnValue =
                                bannerBean.getReturnValue();
                        stringList = new ArrayList<String>();//图片集合
                        for (int i = 0; i < returnValue.size(); i++) {
                            stringList.add(returnValue.get(i).getAdImgUrl().toString());
                        }
                        banner.setImages(stringList);
                        banner.setImageLoader(new GlideImageLoder());
                        banner.setDelayTime(1500);
                        banner.start();
                        banner.setOnBannerListener(new OnBannerListener() {
                            @Override
                            public void OnBannerClick(int position) {
//                                Toast.makeText(getContext(),"AAAA"+position,Toast.LENGTH_SHORT).show();
                                Intent intent = new Intent(getContext(), DetailActivity.class);
                                intent.putExtra("adLinkUrl", returnValue.get(position).getAdLinkUrl());
                                startActivity(intent);
                            }
                        });
                    }
                });
    }


    //请求小喇叭数据
    private void initTrumpet() {
        String trumpeturl = Constants.TRUMPETURL;
        OkHttpUtils.get().url(trumpeturl).build().execute(new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {
                //Log.e(TAG, "首页请求失败==" + e.getMessage());
            }

            @Override
            public void onResponse(String response) {
                //Log.e(TAG, "首页请求成功==" + response);
                //解析数据
                processTrumpetData(response);
            }

            private void processTrumpetData(String response) {

                TrumpetBean trumpetBean = JSON.parseObject(response, TrumpetBean.class);
                List<TrumpetBean.ReturnValueBean> returnValue = trumpetBean.getReturnValue();
                List list = new ArrayList<String>();


                for (int i = 0; i < returnValue.size(); i++) {
                    String str = " 恭喜 " + returnValue.get(i).getNickName()
                            + " 夺取 " + returnValue.get(i).getProductName();
                    list.add(str);
                }
                marqueeView.startWithList(list);
            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }


    @Override
    public void onClick(View view) {
        Boolean isSlected = true;
        Fragment fragment = null;
        switch (view.getId()) {
            case R.id.banner://banner
                initData();
                break;
            case R.id.iv_new_recharge://新人充值有豪礼
                Intent intent = new Intent(getActivity(), NewrechargeActivity.class);
                startActivity(intent);
                break;
            case R.id.tv_classify://分类
                Intent classifyintent = new Intent(getContext(), ClassfityActivity.class);
                startActivity(classifyintent);
                break;
            case R.id.tv_showlist://晒单
                startActivity(new Intent(getContext(), ShowListActivity.class));
                break;
            case R.id.tv_Recharge://充值
//                Intent i = new Intent(getContext(), RechargeActivity.class);
//                startActivity(i);
                Intent i = new Intent(getContext(), UserAccountActivity.class);
                startActivity(i);
                break;
            case R.id.tv_pk://pk
                startActivity(new Intent(getContext(), DoubleActivity.class));
                break;
            case R.id.tv_service://客服
                initPopuWindow(service);
                break;
            case R.id.ll_qa://常见问题
                Intent qa = new Intent(getContext(), CommonQuestionActivity.class);
                startActivity(qa);
                popupWindow.dismiss();
                break;
            case R.id.ll_servicecall://客服电话
                showDialog(mContext);
                break;
            case R.id.iv_fork://关闭窗口
                popupWindow.dismiss();
                break;
            case R.id.tv_callphone://呼叫
                phone = call.getText().toString();
                call(phone);
                break;
            case R.id.tv_addto_contact://添加到手机联系人
                createcontact();
                break;
            case R.id.tv_newcreate://新建联系人
                Intent addIntent = new Intent(Intent.ACTION_INSERT, Uri.withAppendedPath(Uri.parse("content://com.android.contacts"), "contacts"));
                addIntent.setType("vnd.android.cursor.dir/person");
                addIntent.setType("vnd.android.cursor.dir/contact");
                addIntent.setType("vnd.android.cursor.dir/raw_contact");
                addIntent.putExtra(android.provider.ContactsContract.Intents.Insert.PHONE, "400 630 5186");
                startActivity(addIntent);
                break;
            case R.id.tv_created://添加到已有联系人
                Intent oldConstantIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
                oldConstantIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
                oldConstantIntent.putExtra(ContactsContract.Intents.Insert.PHONE, "400 630 5186");
                oldConstantIntent.putExtra(ContactsContract.Intents.Insert.PHONE_TYPE, 3);
                startActivity(oldConstantIntent);
                break;
//            case R.id.arrowtop:
//                ivArrowtop.setImageResource(R.drawable.arrow_bottom_checked);
//                break;
//            case R.id.arrow_bottom:
//                arrowbottom.setImageResource(R.drawable.arrow_bottom_checked);
//                break;
        }
    }
}

